package com.zimmur.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.mysql.fabric.xmlrpc.base.Array;
import com.zimmur.common.ConstData;
import com.zimmur.common.ReturnJsonEntity;
import com.zimmur.common.StatusCodeEnum;
import com.zimmur.model.base.AdBanner;
import com.zimmur.model.base.AppVersion;
import com.zimmur.model.base.Express;
import com.zimmur.model.dto.UserDTO;
import com.zimmur.model.system.GlobalConfig;
import com.zimmur.service.IVerifyMobileService;
import com.zimmur.service.RedisCacheUtil;
import com.zimmur.service.account.IMobileSendTimersService;
import com.zimmur.service.base.IAdBannerService;
import com.zimmur.service.base.IAppVersionService;
import com.zimmur.service.base.IExpressService;
import com.zimmur.tools.FileContentTypeUtil;
import com.zimmur.tools.FunctionUtil;
import com.zimmur.tools.GenerateQrCodeUtil;
import com.zimmur.tools.JwtTokenUtil;
import com.zimmur.tools.PublicKey;

@RestController  
@RequestMapping("/system") 
public class SystemController extends BaseController {
	private static Logger log=LoggerFactory.getLogger(SystemController.class);
	@Resource
	private IVerifyMobileService verifyMobileService;
	@Resource
	private IMobileSendTimersService mobileSendTimersService;
	@Resource
	private IExpressService expressService;
	@Resource
	private IAdBannerService abBannerService;
	@Resource
	private IAppVersionService appVersionService;
	@Resource(name = "trackerClient")
	private TrackerClient trackerClient;
	
	@Resource(name="taskExecutor")
	private ThreadPoolTaskExecutor taskExecutor;
	
	@Value("#{spingMvcProperties['image.broweurl']}")
	private String imgUrl;
	@Value("#{spingMvcProperties['System.GuestId']}")
	private String guessUserId;
	@Value("#{spingMvcProperties['public.key']}")
	private String publicKey;
	@Resource
	private RedisCacheUtil<String> redisCacheUtil;
	@Resource
	private JwtTokenUtil jwtTokenUtil;
	
	 @RequestMapping(value="/sendcode",method=RequestMethod.GET)  
	 public ReturnJsonEntity sendcode(){  
		
		ReturnJsonEntity entity = new ReturnJsonEntity();
		entity.setData("");
		StatusCodeEnum statusCodeEnum = StatusCodeEnum.CODE100100;
		entity.setMsg(statusCodeEnum.getMsg());
		try {
			
			entity.setMsg(ConstData.VERIFY_MOBILE_MESSAGE_SUCCESS);
			
			String mobileNo = getParam("mobileNo");
			String ipAddr = getRemoteIp();
			if(!mobileNo.equals("") && FunctionUtil.isMobile(mobileNo)){
				sendMobileCode(mobileNo, ipAddr);
				statusCodeEnum = StatusCodeEnum.CODE000000;
			}else{
				statusCodeEnum=StatusCodeEnum.CODE100104;
			}
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		
		entity.setCode(statusCodeEnum.getCode());
		
		return entity;
	 }
	 /**
	  * 发送手机邀请码
	  * @param mobileNo
	  * @param IP
	  */
	 private void sendMobileCode(final String mobileNo,final String IP){
		 
		 taskExecutor.execute(new Runnable() {
				public void run() {
					/*IPDataHandler ipDataHandler = new IPDataHandler();
					String country = ipDataHandler.getCurrentProvinceAndCity(IP);
					if(!"".equals(country) && !country.equals("中国")){
						return;
					}*/
					//if(!mobileNo.equals("") && FunctionUtil.isMobile(mobileNo)){
						//限制10分钟6条
						/*if(mobileSendTimersService.checkMobileSendTimers(mobileNo,IP,6)){
							verifyMobileService.insertNewVerify(mobileNo);
						}*/
						verifyMobileService.insertNewVerify(mobileNo);
					//}
				}
			});
	 }
	 @RequestMapping(value="/config",method=RequestMethod.GET)
	 public GlobalConfig sysconfig(){
		 GlobalConfig config = new GlobalConfig();
		 config.setImgurl(imgUrl);
		 return config;
	 }
	 
	//获取默认快递
	 @RequestMapping(value="/getdefaultexpress",method = RequestMethod.GET)
	public ReturnJsonEntity getDefaultExpress(){
		ReturnJsonEntity entity = new ReturnJsonEntity();
		StatusCodeEnum status = StatusCodeEnum.CODE100000;
		try {
			Express express = expressService.selectDefaultExpress();
			if(express != null){
				entity.setData(express);
			}
			status = StatusCodeEnum.CODE000000;
		} catch (Exception er) {
			log.error(er.getMessage());
			status = StatusCodeEnum.CODE100000;
		}
		entity.setCode(status.getCode());
		entity.setMsg(status.getMsg());
		return entity;
	}
	 //获取快递信息
	 @RequestMapping(value="/express",method = RequestMethod.GET)
	 public ReturnJsonEntity getExpressList(){
		ReturnJsonEntity entity = new ReturnJsonEntity();
		StatusCodeEnum status = StatusCodeEnum.CODE100000;
		try {
			List<Express> list = expressService.selectList();
			if(!list.isEmpty()){
				entity.setData(list);
			}else{
				entity.setData(new Array());
			}
			status = StatusCodeEnum.CODE000000;
		} catch (Exception er) {
			log.error(er.getMessage());
			status = StatusCodeEnum.CODE100000;
			entity.setData(new Array());
		}
		entity.setCode(status.getCode());
		entity.setMsg(status.getMsg());
		return entity;

	 }
	 
	 //运费计算
	 @RequestMapping(value="/calcexpressfee",method = RequestMethod.GET)
	 public ReturnJsonEntity calcExpressFee(){
		ReturnJsonEntity entity = new ReturnJsonEntity();
		StatusCodeEnum status = StatusCodeEnum.CODE100000;

		try {
			//String province = getParam("province");
			//String city = getParam("city");
			//String area = getParam("area");
			String expressCode = getParam("expressCode");
			Express express =  expressService.selectByExpressCode(expressCode);
			if(express != null){
				Map<String, Object> map = new HashMap<>();
				map.put("fee", express.getTopPrice());
				entity.setData(map);
				status = StatusCodeEnum.CODE000000;
			}
		} catch (Exception er) {
			log.error(er.getMessage());
			status = StatusCodeEnum.CODE100000;
		}
		entity.setCode(status.getCode());
		entity.setMsg(status.getMsg());
		return entity;
	}
	/**
	 * 获取推荐广告
	 * @return
	 */
	@RequestMapping(value="/adlist",method=RequestMethod.GET)
	public ReturnJsonEntity getAdBannerList() {
		ReturnJsonEntity entity = new ReturnJsonEntity();
		StatusCodeEnum status = StatusCodeEnum.CODE100000;

		try {
			Integer moduleId = getIntParam("moduleId");
			List<AdBanner> list = abBannerService.selectAdList(moduleId);
			if (!list.isEmpty()) {
				entity.setData(list);
				status = StatusCodeEnum.CODE000000;
			}else{
				entity.setData(new ArrayList<>());
			}
		} catch (Exception er) {
			log.error(er.getMessage());
			status = StatusCodeEnum.CODE100000;
			entity.setData(new ArrayList<>());
		}
		entity.setCode(status.getCode());
		entity.setMsg(status.getMsg());
		return entity;
	}
	/**
	 * 获取游客Token,id,public
	 * @return
	 */
	@RequestMapping(value="/guesstoken",method=RequestMethod.GET)
	public ReturnJsonEntity getGuessToken(){
		ReturnJsonEntity entity = new ReturnJsonEntity();
		StatusCodeEnum status = StatusCodeEnum.CODE100000;
		try {
			//获取token
			UserDTO userDTO = new UserDTO(guessUserId,guessUserId);
			String token = jwtTokenUtil.create(userDTO);
			Map<String, String> map = new HashMap<>();
			map.put("token", token);
			map.put("userId", guessUserId);	
			
			//获取publicKey
			String strValue=PublicKey.getKey(redisCacheUtil, publicKey);
			map.put("publicKey", strValue);
			
			entity.setData(map);
			status = StatusCodeEnum.CODE000000;
			
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		entity.setCode(status.getCode());
		entity.setMsg(status.getMsg());
		return entity;
	}
	/**
	 * Android版本升级检查
	 * @return
	 */
	@RequestMapping(value="/checkupgrade",method=RequestMethod.GET)
	public ReturnJsonEntity checkVersion(@RequestParam("versionNo")Integer version){
		ReturnJsonEntity entity = new ReturnJsonEntity();
		StatusCodeEnum status = StatusCodeEnum.CODE100000;
		entity.setMsg("当前已经是最新版本!");
		try {
			AppVersion versionInfo = appVersionService.checkVersion(version);
			if(versionInfo !=null){
				status = StatusCodeEnum.CODE000000;
				entity.setMsg("新版本升级");
				entity.setData(versionInfo);
			}
		}catch (Exception er) {
			log.error(er.getMessage());
			status = StatusCodeEnum.CODE100000;
			entity.setData(new HashMap<>());
			entity.setMsg("当前已经是最新版本!");
			
		}
		entity.setCode(status.getCode());
		return entity;
	}
	/**
	 * Android版本升级
	 */
	@RequestMapping("/versionupgrade")
	public ReturnJsonEntity androidUpgrade(@RequestParam(value="versionNo",required=true)Integer version){
		ReturnJsonEntity entity = new ReturnJsonEntity();
		StatusCodeEnum status = StatusCodeEnum.CODE100000;
		try {
			AppVersion versionInfo = appVersionService.getVersion(version);
			if(versionInfo !=null){
				status = StatusCodeEnum.CODE000000;
				byte[] bytes= downloadFdfsFile(versionInfo.getFdGroup(), versionInfo.getFdStorageId());
				if(bytes != null){
					long fileLength = versionInfo.getFileSize();
					HttpServletResponse response = getResponse();
					response.setContentType(FileContentTypeUtil.getcontentType("apk"));  
			        response.setHeader("Content-disposition", "attachment; filename=popolook"+version+".apk");  
			        response.setHeader("Content-Length", String.valueOf(fileLength));  
					InputStream sbs = new ByteArrayInputStream(bytes);
					
					BufferedInputStream bis = null;
					BufferedOutputStream bos = null;
					try {
						bis = new BufferedInputStream(sbs);
						 bos = new BufferedOutputStream(getResponse().getOutputStream());  
				        byte[] buff = new byte[2048];  
				        int bytesRead;  
				        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
				            bos.write(buff, 0, bytesRead);  
				        }  
				        sbs.close();
					} catch (Exception e) {
						log.error(e.getMessage());
					}finally{
						if(sbs != null){
							sbs.close();
						}
						try {
							 if(bis != null)
								 bis.close();
						} catch (IOException e) {
							e.printStackTrace();
						}  
					     try {
					    	 if(bos != null)
					    		 bos.close();
						} catch (IOException e) {
							e.printStackTrace();
						}  
					}
				}
				
			}
		}catch (Exception er) {
			log.error(er.getMessage(),er);
			status = StatusCodeEnum.CODE100000;
			entity.setData(new HashMap<>());
			
		}
		entity.setCode(status.getCode());
		entity.setMsg(status.getMsg());
		return entity;
	}
	
	@RequestMapping(value="/qrcode")
	public void getQRCode(String codeUrl){
		if(org.springframework.util.StringUtils.isEmpty(codeUrl))
			return;
		GenerateQrCodeUtil.encodeQrcode(codeUrl, this.getResponse());
	}
	/**
	 * 获取Fdfs文件
	 * @param groupName
	 * @param storageId
	 * @return
	 */
	private byte[] downloadFdfsFile(String groupName,String storageId){
		byte[] b=null;
		try {

            TrackerServer trackerServer = trackerClient.getConnection(); 
            StorageServer storageServer = null;

            StorageClient storageClient = new StorageClient(trackerServer, storageServer); 
            b = storageClient.download_file(groupName,storageId); 
            
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
		return b;
	}
}
